import html2Canvas from 'html2canvas';
import JsPDF from 'jspdf';
//设置字体
import '../assets/font/STZHONGS-normal.js';
function htmlPdf(title, html) {
  html2Canvas(html, {
    allowTaint: false,
    taintTest: false,
    logging: false,
    useCORS: true,
    dpi: window.devicePixelRatio * 1,
    scale: 1 // 按比例增加分辨率
  }).then(canvas => {
    var pdf = new JsPDF('p', 'mm', 'a4'); // A4纸，纵向
	// pdf.addFileToVFS('MyCustomFont.ttf', myCustomFont); // 添加字体文件到 VFS
	// pdf.addFont('MyCustomFont.ttf', 'MyCustomFont', 'normal'); // 添加字体
	pdf.setFont('STZHONGS'); // 设置字体
	pdf.setFontSize(10); // 设置标题字体大小
    var ctx = canvas.getContext('2d');
    var a4w = 190; var a4h = 277; // A4大小，210mm x 297mm
    var imgHeight = Math.floor(a4h * canvas.width / a4w); // 换算一页图像的像素高度
    var renderedHeight = 0;

    while (renderedHeight < canvas.height) {
      var page = document.createElement('canvas');
      page.width = canvas.width;
      page.height = Math.min(imgHeight, canvas.height - renderedHeight); // 可能内容不足一页

      // 剪裁并画到canvas中
      page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0);
      if (renderedHeight === 0) { // 只在第一页顶部添加标题
        pdf.text(title, 105, 10, { align: 'center' }); // 105是A4纸宽度一半，10是距离顶部的位置
      }
      pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 20, a4w, Math.min(a4h, a4w * page.height / page.width)); // 添加图像到页面

      renderedHeight += imgHeight;
      if (renderedHeight < canvas.height) {
        pdf.addPage();
        // 如果希望在每一页都添加标题，取消下面的注释
        // pdf.text(title, 105, 10, { align: 'center' });
      }
    }
    // 保存文件
    pdf.save(title + '.pdf');
  });
}

export default htmlPdf;
